package managedbean.Sales;

import entity.AccessRole;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.ejb.EJB;
import session.stateless.EmployeeSessionBeanLocal;
import session.stateless.CustomerSessionBeanLocal;
import javax.faces.bean.ManagedProperty;
import managedbean.UserSessionManagerBean;
import entity.Address;
import entity.Employee;
import entity.Customer;
import entity.Job;
import entity.PurchaseItem;
import entity.PurchaseOrder;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import session.stateless.AccessRoleSessionBeanLocal;
import session.stateless.LogSessionBeanLocal;
import session.stateless.MessageSessionBeanLocal;

@ManagedBean(name = "customerManagerBean")
@RequestScoped
public class CustomerManagerBean {

    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    @EJB
    private EmployeeSessionBeanLocal employeeSessionBeanLocal;
    @EJB
    private CustomerSessionBeanLocal customerSessionBeanLocal;
    @EJB
    private MessageSessionBeanLocal messageSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    @EJB
    private AccessRoleSessionBeanLocal accessRoleSessionBeanLocal;
    private String loadAddCustomer;
    private String loadSearchCustomer;
    private String loadUpdateCustomer;
    private String loadAssignExecutive;
    private String request;
    // <editor-fold defaultstate="collapsed" desc="Customer attributes. Click on the + sign on the left to edit the code.">
    private Long custId;
    private String userId;
    private Employee employee = new Employee();
    private String email;
    private String firstName;
    private String lastName;
    private String company;
    private String title;
    private String status;
    private String industry;
    private Integer phone;
    private Address companyAddress;
    private String street;
    private String country;
    private String city;
    private Integer postal;
    private Double revenue;
    private Integer numEmployee;
    private String description;
    private String selectedLead;
    private ArrayList<Address> addresses;
    private ArrayList<Address> billingAddresses = new ArrayList<Address>();
    private ArrayList<Address> shippingAddresses = new ArrayList<Address>();
    private ArrayList<Employee> employees;
    private String type;
    private Boolean assigned;
    private static Customer customer = new Customer();
    private ArrayList<Customer> customers = new ArrayList<Customer>();
    //</editor-fold>

    public String getLoadSearchCustomer() {
        userId = userSessionManagerBean.getUserId();

        String temp = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("request");

        if (temp != null) {

            userSessionManagerBean.setSelectedItem((String) temp + ".xhtml");

            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/searchCustomer.xhtml");

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        customers.clear();
        request = (String) userSessionManagerBean.getSelectedItem();
        if ((request.compareTo("updateCustomer.xhtml") == 0) || (request.compareTo("addJob.xhtml") == 0) || (request.compareTo("addPurchaseOrder.xhtml") == 0)) {
            customers = customerSessionBeanLocal.getCustomers(userId);
        } else if (request.compareTo("assignExecutive.xhtml") == 0) {
            customers = customerSessionBeanLocal.getCustomers(false, 1);
        } else if (request.compareTo("viewCustomer.xhtml") == 0) {
            customers = customerSessionBeanLocal.getCustomers();
        } else if (request.compareTo("addCredit.xhtml") == 0) { //get customers who do not have credit account yet
            customers = customerSessionBeanLocal.getCustomers(false, 2);
        } else if (request.compareTo("updateCredit.xhtml") == 0) { //get customers who have credit account already
            customers = customerSessionBeanLocal.getCustomers(true, 2);
        } else if (request.compareTo("viewCredit.xhtml") == 0) { //get customers who have credit account already
            customers = customerSessionBeanLocal.getCustomers(true, 2);
        } else if (request.compareTo("cancelSalesOrder.xhtml") == 0) { //get customers managed by userId
            customers = customerSessionBeanLocal.getCustomers(userId);
        } else if (request.compareTo("creditCheck.xhtml") == 0) { //get customers who have been assigned
            customers = customerSessionBeanLocal.getCustomers(true, 1);
        } else if (request.compareTo("addPayment.xhtml") == 0) { //get customers who have credit account already
            customers = customerSessionBeanLocal.getCustomers(true, 2);
        } else if (request.compareTo("payments.xhtml") == 0) {
            customers = customerSessionBeanLocal.getCustomers(true, 2);
        } else if (request.compareTo("invoices.xhtml") == 0) {
            customers = customerSessionBeanLocal.getCustomers(true, 2);
        } else if (request.compareTo("receipts.xhtml") == 0) {
            customers = customerSessionBeanLocal.getCustomers(true, 2);
        } else if (request.compareTo("mySalesOrders.xhtml") == 0) {
            customers = customerSessionBeanLocal.getCustomers(userId);
        } else if (request.compareTo("salesOrders.xhtml") == 0) {
            customers = customerSessionBeanLocal.getCustomers(true, 2);
        }

        return null;
    }

    public String getLoadAddCustomer() {
        refreshCustomer();
        return null;
    }

    public String getLoadUpdateCustomer() {
        refreshCustomer();
        return null;
    }

    public String getLoadAssignExecutive() {
        employees = employeeSessionBeanLocal.getEmployees("Sales - Direct sales");
        for (int i = 0; i < employees.size(); i++) {
            employees.get(i).setContactOffice(0);
        }

        for (Customer c : customerSessionBeanLocal.getCustomers(true, 1)) {
            for (int i = 0; i < employees.size(); i++) {
                if (c.getEmployee().getUserId().compareTo(employees.get(i).getUserId()) == 0) {
                    Integer current = employees.get(i).getContactOffice() + 1;
                    employees.get(i).setContactOffice(current);
                }
            }
        }
        refreshCustomer();
        return null;
    }

    // <editor-fold defaultstate="collapsed" desc="Getter & Setter methods. Click on the + sign on the left to edit the code.">
    /**
     * @param loadAssignExecutive the loadAssignExecutive to set
     */
    public void setLoadAssignExecutive(String loadAssignExecutive) {
        this.loadAssignExecutive = loadAssignExecutive;
    }

    /**
     * @return the customer
     */
    public void setLoadUpdateCustomer(String loadUpdateCustomer) {
        this.loadUpdateCustomer = loadUpdateCustomer;
    }

    public Customer getCustomer() {
        return customer;
    }

    /**
     * @param aCustomer the customer to set
     */
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public void setLoadAddCustomer(String loadAddCustomer) {
        this.loadAddCustomer = loadAddCustomer;
    }

    public EmployeeSessionBeanLocal getEmployeeSessionBeanLocal() {
        return employeeSessionBeanLocal;
    }

    /**
     * @param employeeSessionLocal the employeeSessionLocal to set
     */
    public void setEmployeeSessionBeanLocal(EmployeeSessionBeanLocal employeeSessionBeanLocal) {
        this.employeeSessionBeanLocal = employeeSessionBeanLocal;
    }

    /**
     * @return the selectedLead
     */
    public String getSelectedLead() {
        return selectedLead;
    }

    /**
     * @param selectedLead the selectedLead to set
     */
    public void setSelectedLead(String selectedLead) {
        this.selectedLead = selectedLead;
    }

    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @return the custId
     */
    public Long getCustId() {
        return custId;
    }

    /**
     * @param custId the custId to set
     */
    public void setCustId(Long custId) {
        this.custId = custId;
    }

    /**
     * @return the employee
     */
    public Employee getEmployee() {
        return employee;
    }

    /**
     * @param employee the employee to set
     */
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the company
     */
    public String getCompany() {
        return company;
    }

    /**
     * @param company the company to set
     */
    public void setCompany(String company) {
        this.company = company;
    }

    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * @return the status
     */
    public String getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * @return the phone
     */
    public Integer getPhone() {
        return phone;
    }

    /**
     * @param phone the phone to set
     */
    public void setPhone(Integer phone) {
        this.phone = phone;
    }

    /**
     * @return the companyAddress
     */
    public Address getCompanyAddress() {
        return companyAddress;
    }

    /**
     * @param companyAddress the companyAddress to set
     */
    public void setCompanyAddress(Address companyAddress) {
        this.companyAddress = companyAddress;
    }

    /**
     * @return the revenue
     */
    public Double getRevenue() {
        return revenue;
    }

    /**
     * @param revenue the revenue to set
     */
    public void setRevenue(Double revenue) {
        this.revenue = revenue;
    }

    /**
     * @return the numEmployee
     */
    public Integer getNumEmployee() {
        return numEmployee;
    }

    /**
     * @param numEmployee the numEmployee to set
     */
    public void setNumEmployee(Integer numEmployee) {
        this.numEmployee = numEmployee;
    }

    /**
     * @return the industry
     */
    public String getIndustry() {
        return industry;
    }

    /**
     * @param industry the industry to set
     */
    public void setIndustry(String industry) {
        this.industry = industry;
    }

    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }

    /**
     * @param description the description to set
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @return the userId
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return the street
     */
    public String getStreet() {
        return street;
    }

    /**
     * @param street the street to set
     */
    public void setStreet(String street) {
        this.street = street;
    }

    /**
     * @return the country
     */
    public String getCountry() {
        return country;
    }

    /**
     * @param country the country to set
     */
    public void setCountry(String country) {
        this.country = country;
    }

    /**
     * @return the city
     */
    public String getCity() {
        return city;
    }

    /**
     * @param city the city to set
     */
    public void setCity(String city) {
        this.city = city;
    }

    /**
     * @return the postal
     */
    public Integer getPostal() {
        return postal;
    }

    /**
     * @param postal the postal to set
     */
    public void setPostal(Integer postal) {
        this.postal = postal;
    }

    /**
     * @return the billingAddresses
     */
    public ArrayList<Address> getBillingAddresses() {
        return billingAddresses;
    }

    /**
     * @param billingAddresses the billingAddresses to set
     */
    public void setBillingAddresses(ArrayList<Address> billingAddresses) {
        this.billingAddresses = billingAddresses;
    }

    /**
     * @return the shippingAddresses
     */
    public ArrayList<Address> getShippingAddresses() {
        return shippingAddresses;
    }

    /**
     * @param shippingAddresses the shippingAddresses to set
     */
    public void setShippingAddresses(ArrayList<Address> shippingAddresses) {
        this.shippingAddresses = shippingAddresses;
    }

    /**
     * @return the type
     */
    public String getType() {
        return type;
    }

    /**
     * @param type the type to set
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @return the Addresses
     */
    public ArrayList<Address> getAddresses() {
        return addresses;
    }

    /**
     * @param Addresses the Addresses to set
     */
    public void setAddresses(ArrayList<Address> addresses) {
        this.addresses = addresses;
    }

    /**
     * @param loadSearchCustomer the loadSearchCustomer to set
     */
    public void setLoadSearchCustomer(String loadSearchCustomer) {
        this.loadSearchCustomer = loadSearchCustomer;
    }

    /**
     * @return the customers
     */
    public ArrayList<Customer> getCustomers() {
        return customers;
    }

    /**
     * @param customers the customers to set
     */
    public void setCustomers(ArrayList<Customer> customers) {
        this.customers = customers;
    }

    /**
     * @return the assigned
     */
    public Boolean getAssigned() {
        return assigned;
    }

    /**
     * @param assigned the assigned to set
     */
    public void setAssigned(Boolean assigned) {
        this.assigned = assigned;
    }

    /**
     * @return the employees
     */
    public ArrayList<Employee> getEmployees() {
        return employees;
    }

    /**
     * @param employees the employees to set
     */
    public void setEmployees(ArrayList<Employee> employees) {
        this.employees = employees;
    }

    //</editor-fold>
    public void refreshCustomer() {
        userId = userSessionManagerBean.getUserId();
        if (userSessionManagerBean.getCustomer() != null) {

            Customer temp = userSessionManagerBean.getCustomer();
            employee = temp.getEmployee();
            userId = employee.getUserId();
            custId = temp.getCustId();
            email = temp.getEmail();
            firstName = temp.getFirstName();
            lastName = temp.getLastName();
            company = temp.getCompany();
            title = temp.getTitle();
            status = temp.getStatus();
            industry = temp.getIndustry();
            phone = temp.getPhone();
            companyAddress = temp.getCompanyAddress();
            street = companyAddress.getStreet();
            country = companyAddress.getCountry();
            city = companyAddress.getCity();
            postal = companyAddress.getPostal();
            revenue = temp.getRevenue();
            numEmployee = temp.getNumEmployee();
            description = temp.getDescription();
            if (temp.getAddresses() != null) {
                for (Address a : temp.getAddresses()) {
                    if (a.getType().compareTo("Billing") == 0) {
                        billingAddresses.add(a);
                    } else {
                        shippingAddresses.add(a);
                    }
                }
            }

            type = temp.getType();
            assigned = temp.getAssigned();
        }
    }

    public void addBAddress(ActionEvent event) {
        try {
            userSessionManagerBean.setSelectedItem("Billing");
            userSessionManagerBean.setCustomer(createCustomerObject());
            boolean found = false;

            if (userSessionManagerBean.getCustomer().getAddresses() == null) {
                userSessionManagerBean.getCustomer().setAddresses(new ArrayList<Address>());
                Address temp = userSessionManagerBean.getCustomer().getCompanyAddress();
                temp.setType("Billing");
                userSessionManagerBean.getCustomer().getAddresses().add(temp);

            } else {
                for (Address a : userSessionManagerBean.getCustomer().getAddresses()) {
                    if (a.getType().compareTo("Billing") == 0) {
                        found = true;
                    }
                }
                if (!found) {
                    Address temp = userSessionManagerBean.getCustomer().getCompanyAddress();
                    temp.setType("Billing");
                    userSessionManagerBean.getCustomer().getAddresses().add(temp);
                }
            }

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/addAddress.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void addSAdddress(ActionEvent event) {
        try {
            userSessionManagerBean.setSelectedItem("Shipping");
            userSessionManagerBean.setCustomer(createCustomerObject());
            boolean found = false;

            if (userSessionManagerBean.getCustomer().getAddresses() == null) {
                userSessionManagerBean.getCustomer().setAddresses(new ArrayList<Address>());
                Address temp = userSessionManagerBean.getCustomer().getCompanyAddress();
                temp.setType("Shipping");
                userSessionManagerBean.getCustomer().getAddresses().add(temp);

            } else {
                for (Address a : userSessionManagerBean.getCustomer().getAddresses()) {
                    if (a.getType().compareTo("Shipping") == 0) {
                        found = true;
                    }
                }
                if (!found) {
                    Address temp = userSessionManagerBean.getCustomer().getCompanyAddress();
                    temp.setType("Shipping");
                    userSessionManagerBean.getCustomer().getAddresses().add(temp);
                }
            }

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/addAddress.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public Customer createCustomerObject() {
        companyAddress = new Address(street, country, city, postal, "Company");
        if (userSessionManagerBean.getCustomer() != null && userSessionManagerBean.getCustomer().getAddresses() != null) {
            addresses = new ArrayList<Address>(userSessionManagerBean.getCustomer().getAddresses());
        }
        Employee employee = getEmployeeSessionBeanLocal().getEmployee(userId);
        Customer customer = new Customer(employee, email, firstName, lastName, company, title, status, phone, companyAddress, revenue, description, numEmployee, industry, addresses, type, assigned);
        customer.setCustId(custId);
        return customer;
    }

    public void addCustomer(ActionEvent event) {

        companyAddress = new Address(street, country, city, postal, "Company");
        if (userSessionManagerBean.getCustomer() != null) {
            addresses = new ArrayList<Address>(userSessionManagerBean.getCustomer().getAddresses());
        }

        billingAddresses = new ArrayList<Address>();
        shippingAddresses = new ArrayList<Address>();
        if (addresses != null) {
            for (Address ad : addresses) {
                if (ad.getType().compareTo("Billing") == 0) {
                    billingAddresses.add(ad);
                } else {
                    shippingAddresses.add(ad);
                }
            }
        }

        if (billingAddresses.size() > 0 && shippingAddresses.size() > 0 && addresses != null) {
            try {
                Customer c = customerSessionBeanLocal.getCustomerByCompany(company);

                if (c == null) {
                    c = customerSessionBeanLocal.getCustomerByEmail(email);

                    if (c == null) { //no existing customer with same email address
                        customerSessionBeanLocal.addCustomer(userId, email, firstName, lastName, company, title, status, phone, companyAddress, revenue, description, numEmployee, industry, addresses, type, false, null);

                        customer = customerSessionBeanLocal.getCustomer(email, Boolean.TRUE);

                        logSessionBeanLocal.addLog("Add customer", "Customer account created: " + customer.getCustId().toString(), "addCustomer.xhtml", userSessionManagerBean.getUserId());

                        try {
                            ArrayList<AccessRole> rlist = accessRoleSessionBeanLocal.getAccessRoles("Assign Exec. ");
                            ArrayList<Employee> employees = employeeSessionBeanLocal.getEmployees(rlist);

                            for (Employee em : employees) {
                                Employee owner = employeeSessionBeanLocal.getEmployee("System");
                                messageSessionBeanLocal.addMessage("System", em.getUserId(), "Assignment of Customer",
                                        "Customer <b>" + customer.getCompany() + "</b> has been created, please assign an executive to handle the customer. "
                                        + "<p><hr/><p>This is a system generated message, no reply is required.", owner);

                                owner = employeeSessionBeanLocal.getEmployee(em.getUserId());
                                messageSessionBeanLocal.addMessage("System", em.getUserId(), "Assignment of Customer",
                                        "Customer <b>" + customer.getCompany() + "</b> has been created, please assign an executive to handle the customer. "
                                        + "<p><hr/><p>This is a system generated message, no reply is required.", owner);
                            }
                        } catch (Exception ex) {//Not employees able to assign executive to customer}
                            ex.printStackTrace();
                            FacesContext.getCurrentInstance().addMessage(null,
                                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
                        }

                        ArrayList<String> al = new ArrayList<String>();
                        al.add("Customer created");
                        al.add("You have successfully created the customer. Please be reminded that you may not have access to this record unless you have been assign to this customer by the sales manager.");
                        al.add("Click on the link to return to ");
                        al.add("continue");
                        al.add("Web_Sales/addCustomer.xhtml");
                        userSessionManagerBean.setSelectedItem(al);

                        FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                                + userSessionManagerBean.getServerName() + ":"
                                + userSessionManagerBean.getServerPort()
                                + "/MerlionERP-war/success.xhtml");
                    } else { //there is an existing customer with same email address
                        FacesContext.getCurrentInstance().addMessage(null,
                                new FacesMessage(FacesMessage.SEVERITY_ERROR, "A customer with the same email address already exists.", ""));
                    }
                } else {
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "A customer with the same company name already exists..", ""));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "A shipping and billing address must be added.", ""));
        }
    }

    public void edit(ActionEvent event) {
        try {
            if (request.compareTo("addJob.xhtml") == 0) {
                Job job = new Job(customer, employeeSessionBeanLocal.getEmployee(userSessionManagerBean.getUserId()), null, null, null, null, null, null);
                userSessionManagerBean.setSelectedItem(job);
                userSessionManagerBean.setRequest("addJob.xhtml");

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/" + request);
            } else if (request.compareTo("addPurchaseOrder.xhtml") == 0) {
                PurchaseOrder po = new PurchaseOrder(null, 0.0, 0.0, 0.0, "Pending", null, null, null, customer, null, 0.0, 0.0);
                List<PurchaseItem> items = new ArrayList<PurchaseItem>();
                po.setPurchaseItems(items);
                userSessionManagerBean.setSelectedItem(po);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/" + request);
            } else if (request.compareTo("addCredit.xhtml") == 0) {
                userSessionManagerBean.setRequest("addCredit.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("updateCredit.xhtml") == 0) {
                userSessionManagerBean.setRequest("updateCredit.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("viewCredit.xhtml") == 0) {
                userSessionManagerBean.setRequest("viewCredit.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("cancelSalesOrder.xhtml") == 0) {
                userSessionManagerBean.setRequest("cancelSalesOrder.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/" + request);
            } else if (request.compareTo("creditCheck.xhtml") == 0) {
                userSessionManagerBean.setRequest("creditCheck.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("addPayment.xhtml") == 0) {
                userSessionManagerBean.setRequest("addPayment.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("payments.xhtml") == 0) {
                userSessionManagerBean.setRequest("payments.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("invoices.xhtml") == 0) {
                userSessionManagerBean.setRequest("invoices.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("receipts.xhtml") == 0) {
                userSessionManagerBean.setRequest("receipts.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Finance/" + request);
            } else if (request.compareTo("mySalesOrders.xhtml") == 0) {
                userSessionManagerBean.setRequest("mySalesOrders.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/" + request);
            } else if (request.compareTo("salesOrders.xhtml") == 0) {
                userSessionManagerBean.setRequest("salesOrders.xhtml");
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/" + request);
            } else {
                userSessionManagerBean.setCustomer(customer);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort() + "/MerlionERP-war/Web_Sales/" + request);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void doneUpdate(ActionEvent event) {
        try {
            custId = userSessionManagerBean.getCustomer().getCustId();
            companyAddress = new Address(street, country, city, postal, "Company");
            employee = getEmployeeSessionBeanLocal().getEmployee(userId);

            if (userSessionManagerBean.getCustomer() != null) {
                addresses = new ArrayList<Address>(userSessionManagerBean.getCustomer().getAddresses());
            }

            Customer temp = customerSessionBeanLocal.getCustomer(email, true);

            if (temp == null) {
                customerSessionBeanLocal.updateCustomer(custId, userId, email, firstName, lastName, company, title, status, phone, companyAddress, revenue, description, numEmployee, industry, addresses, type, assigned);
            } else if (temp.getCustId() == custId) {
                customerSessionBeanLocal.updateCustomer(custId, userId, email, firstName, lastName, company, title, status, phone, companyAddress, revenue, description, numEmployee, industry, addresses, type, assigned);
            }

            logSessionBeanLocal.addLog("Update customer", "Customer account updated: " + custId, "updateCustomer.xhtml", userSessionManagerBean.getUserId());

            ArrayList<String> al = new ArrayList<String>();
            al.add("Customer updated");
            al.add("You have successfully updated the customer. ");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_Sales/searchCustomer.xhtml?request=updateCustomer");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/success.xhtml");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void assign(ActionEvent event) {
        try {
            custId = userSessionManagerBean.getCustomer().getCustId();
            userId = employee.getUserId();
            customerSessionBeanLocal.assignExecutive(custId, userId);

            Employee owner = employeeSessionBeanLocal.getEmployee("System");
            messageSessionBeanLocal.addMessage("System", userId, "Assignment of Customer",
                    "Customer <b>" + userSessionManagerBean.getCustomer().getCompany() + "</b> has been assigned to you by "
                    + "<b>" + userSessionManagerBean.getName() + "</b>."
                    + "<p><hr/><p>This is a system generated message, no reply is required.", owner);

            owner = employeeSessionBeanLocal.getEmployee(userId);
            messageSessionBeanLocal.addMessage("System", userId, "Assignment of Customer", //to send message to executive
                    "Customer <b>" + userSessionManagerBean.getCustomer().getCompany() + "</b> has been assigned to you by "
                    + "<b>" + userSessionManagerBean.getName() + "</b>."
                    + "<p><hr/><p>This is a system generated message, no reply is required.", owner);

            logSessionBeanLocal.addLog("Assign executive", "Assign executive: " + userId + " assigned to customer account: " + custId, "assignExecutive.xhtml", userSessionManagerBean.getUserId());

            ArrayList<String> al = new ArrayList<String>();
            al.add("Customer assignment completed");
            al.add("You have successfully assigned the customer to the executive. The executive will be granted control to access the customer information. ");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_Sales/searchCustomer.xhtml?request=assignExecutive");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/success.xhtml");

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void back(ActionEvent e) {
        try {
            if (e.getComponent().getId().equals("btnBack")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Sales/searchCustomer.xhtml"); //go back to searchcustomer.xhtml
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
